﻿// controller to consolidate the display of the images in the search results
angular.module('app.search').controller('SearchResultsContainerController', ['$scope', 'authService', 'dataService', '$modal', '$window',
	function ($scope, authService, dataService, $modal, $window) {
		'use strict';
		$scope.model = {};
		// define the authenticated user property to get the user from the auth service
		Object.defineProperty($scope.model, "authUser", {
			get: function () { return authService.authStatus.authenticatedUser; },
			enumerable: true,
		});

		var instance = this;
		$scope.selectedImage = null;
		$scope.loading = true;
		$scope.hasResults = false;
		$scope.message = '';
		// retry search information
		$scope.retry = {
			allow: false,
			retrySearch: undefined,
			setRetryMethod: function (method) {
				$scope.retry.allow = method !== null && method !== undefined;
				$scope.retry.retrySearch = method;
			}
		};
		// images model for paging, all items, page items, and changing pages
		$scope.images = {
			items: [],
			paging: {
				size: 16,
				number: 1,
				total: 1
			},
			previousPage: function () {
				// cannot go lower than page one
				if ($scope.images.paging.number < 2) {
					return;
				}
				// decreates the page and set the items
				$scope.images.paging.number--;
				$scope.images.setPageItems();
			},
			nextPage: function () {
				// cannot go over the total number of pages
				if ($scope.images.paging.number + 1 > $scope.images.paging.total) {
					return;
				}
				// increase page number and set page items
				$scope.images.paging.number++;
				$scope.images.setPageItems();
			},
			pageItems: [],
			setPageItems: function () {
				var startIndex = ($scope.images.paging.number - 1) * $scope.images.paging.size;
				var endIndex = $scope.images.paging.number * $scope.images.paging.size;
				// set the page items to the start and ending points
				$scope.images.pageItems = $scope.images.items.slice(startIndex, endIndex);
			},
			setItems: function (items) {
				// set the items to the passed collection
				$scope.images.items = items;
				// reset the page to the first page and calculate the total number of pages
				$scope.images.paging.number = 1;
				$scope.images.paging.total = Math.ceil($scope.images.items.length / $scope.images.paging.size);
				// set the page items
				$scope.images.setPageItems();
			}
		};

		// view full sized image
		$scope.viewImage = function (image) {
			var scope = $scope.$new();
			scope.image = image;
			// open the modal
			$modal.open({
				templateUrl: '/app/user/views/ViewFullImage.html',
				scope: scope
			});
		};;
		// handle the get images response
		$scope.handleGetImagesResponse = function (response) {
			// turn off the loading status
			$scope.loading = false;
			if (response.data.Successful && response.data.Content.length > 0) {
				// if successful and has items, set the items and show results
				$scope.hasResults = true;
				$scope.images.setItems(response.data.Content);
				$scope.message = '';
			}
			else {
				// failed or has no items
				$scope.images.items = [];
				$scope.images.paging.number = 1;
				$scope.images.paging.total = 1;
				$scope.hasResults = false;
				$scope.message = response.data.Message;
			}
		};
		// check if an image is a favorite image
		$scope.isImageAFavorite = function (imageId) {
			// if not authenticated, return false
			if ($scope.model.authUser === undefined || $scope.model.authUser === null) {
				return false;
			}
			// check for ID in fav images list
			return $scope.model.authUser.FavoriteImageIds.indexOf(imageId) >= 0;
		};
		// set an image as a favorite
		this.handleSetImageAsFavoriteResponse = function (response) {
			var data = response.data;
			// failed response or no data
			if (data === null || data === undefined ||
				data.Content === null || data.Content === undefined) {
				return;
			}
			// if not authenticated user, return
			if ($scope.model.authUser === undefined || $scope.model.authUser === null) {
				return;
			}
			// add the image to the favorite images lists for the user
			$scope.model.authUser.FavoriteImages.push(data.Content);
			$scope.model.authUser.FavoriteImageIds.push(data.Content.ImageId);
		};

		$scope.setImageAsFavorite = function (imageId) {
			if ($scope.isImageAFavorite(imageId)) {
				return;
			}

			if ($scope.model.authUser === undefined || $scope.model.authUser === null) {
				return;
			}

			dataService.upload('FavoriteImage', { ImageId: imageId })
				.then(instance.handleSetImageAsFavoriteResponse);
		};

		this.findFavoriteImageId = function (imageId) {
			for (var index in $scope.model.authUser.FavoriteImages) {
				var favImg = $scope.model.authUser.FavoriteImages[index];
				if (favImg.ImageId === imageId) {
					return { id: favImg.Id, index: index };
				}
			}

			return null;
		};
		// remove an image as a favorite
		$scope.removeImageAsFavorite = function (imageId) {
			// find the favorite image by image id
			var found = instance.findFavoriteImageId(imageId);
			if (found === null) {
				return;
			}
			// upload the delete favorite image
			dataService.upload('FavoriteImage', { Id: found.id, IsDeleted: true })
				.then(function (response) {
					var data = response.data;
					if (data === null || data === undefined ||
						data.Content !== null || !data.Successful) {
						return;
					}
					// find the image in the favorite images lists
					var idIndex = $scope.model.authUser.FavoriteImageIds.indexOf(imageId);
					// remove the favorites from teh lists
					$scope.model.authUser.FavoriteImages.splice(found.index, 1);
					$scope.model.authUser.FavoriteImageIds.splice(idIndex, 1);
				});
		};
		// go to the previous page
		$scope.goBack = function () {
			$window.history.back();
		};
	}]);